let source = [{
    id: 1,
    pid: 0,
    name: 'body'
  }, {
    id: 2,
    pid: 1,
    name: 'title'
  }, {
    id: 3,
    pid: 2,
    name: 'div'
  },
{
    id:4,
    pid:1,
    name:'script'
}]

function BeTree(obj) {
    let result = []
    let map = {}
    obj.forEach(item => {
        map[item.id] = item
    })

    obj.forEach(item => {
        let parent = map[item.pid]
        if(parent) {
            (parent.children || (parent.children = [])).push(item)
        }
        else {
            result.push(item)
        }
    })
    return result
}

console.log(BeTree(source));